package com.gsmvn.ngamgaixinh;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.appota.vn.social.common.CommonStatic;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.model.GraphObject;
import com.google.gson.Gson;
import com.gsmvn.ngamgaixinh.SqlDataBaseHelper.CheckNewPhotoTable;
import com.readystatesoftware.viewbadger.BadgeView;

public class CheckNewPhotoService extends Service {

	public static final String ACTIOn = "checknewphotoservice.congaixinh";
	private static String firts_img_url;
	private int new_photo_count;
	public Bitmap bitmap;
	public ImageView img;
	public View myView;
	public WindowManager wm;
	public WindowManager.LayoutParams params;
	public BadgeView badgeView;
	private NotificationManager mNotificationManager;

	@Override
	public void onCreate() {
		super.onCreate();
		// System.exit(0);
		params = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_PHONE,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);
		params.gravity = Gravity.TOP | Gravity.LEFT;
		wm = (WindowManager) getSystemService(WINDOW_SERVICE);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		if (intent != null) {
			String action = intent.getAction();
			if (getSharedPreferences("congaixinh", 0).getBoolean(
					"notification", true)) {
				if (action.equals(ACTIOn)) {
					Log.e("", "sv recived  "+action);
					boolean isstop = intent.getBooleanExtra("stop", false);
					if (isstop) {
						stopSelf();
						return;
					}
					
					Cursor c = getContentResolver().query(
							CongaiXinhContentProvider.CONTENT_URI, null, null,
							null, null);
					if (c.moveToFirst()) {
						String create_time = c
								.getString(c
										.getColumnIndex(CheckNewPhotoTable.Column.Create_time));
						if (create_time != null) {
							String fqlQuery = "{";
							for (int i = 0; i < CommonStatic.arr.length; i++) {
								fqlQuery = fqlQuery.concat("'photos"
										+ CommonStatic.arr[i] + "':");
								fqlQuery = fqlQuery
										.concat("'select created,caption,images from photo where album_object_id="
												+ CommonStatic.arr_id[i]
												+ " and created>"
//												 +"1368670700"
												+ create_time

												+ "',");
							}
							fqlQuery = fqlQuery.concat("}");
							Bundle params = new Bundle();
							params.putString("q", fqlQuery);
							Request request = new Request(null, "/fql", params,
									HttpMethod.GET, new Request.Callback() {

										@Override
										public void onCompleted(
												Response response) {
											// TODO Auto-generated method stub
											initListPhoto(response, false);
										}
									});
							RequestAsyncTask asyncTask = new RequestAsyncTask(
									request);
							asyncTask.execute();
						}
					}
					c.close();
				}
				
			} else {
				stopSelf();
			}

		}
	}

	private void initListPhoto(Response response, boolean showfloating) {
		Gson gson = new Gson();
		try {
			GraphObject graphObject = response.getGraphObject();
			if (graphObject != null) {
				JSONObject grap = graphObject.getInnerJSONObject();
				JSONArray array = grap.getJSONArray("data");
				int data_count = array.length();
				if (data_count > 0) {
					int object_count2 = array.getJSONObject(0)
							.getJSONArray("fql_result_set").length();
					Log.e("", " object_count2 " + object_count2);
					int object_count1 = array.getJSONObject(1)
							.getJSONArray("fql_result_set").length();
					int object_count3 = array.getJSONObject(2)
							.getJSONArray("fql_result_set").length();
					int object_count4 = array.getJSONObject(3)
							.getJSONArray("fql_result_set").length();
					Log.e("", " object_count1 " + object_count1);
					Log.e("", " object_count3 " + object_count3);
					firts_img_url = "";
					String created_temp = "";
					if (array.getJSONObject(0).getJSONArray("fql_result_set")
							.length() > 0) {
						if (array.getJSONObject(0)
								.getJSONArray("fql_result_set")
								.getJSONObject(0).getJSONArray("images")
								.length() > 0) {
							created_temp = array.getJSONObject(0)
									.getJSONArray("fql_result_set")
									.getJSONObject(0).getString("created");
							firts_img_url = array.getJSONObject(0)
									.getJSONArray("fql_result_set")
									.getJSONObject(0).getJSONArray("images")
									.getJSONObject(0).getString("source");
							Log.e("", "created_temp 0" + created_temp);
						}

					}
					if (array.getJSONObject(1).getJSONArray("fql_result_set")
							.length() > 0) {
						if (array.getJSONObject(1)
								.getJSONArray("fql_result_set")
								.getJSONObject(0).getJSONArray("images")
								.length() > 0) {
							String created_temp1 = array.getJSONObject(1)
									.getJSONArray("fql_result_set")
									.getJSONObject(0).getString("created");
							Log.e("",
									"created_temp.equals() 1 "
											+ created_temp.equals("")
											+ "created_temp " + created_temp);
							if (!created_temp.equals("")) {
								if (Long.valueOf(created_temp1) > Long
										.valueOf(created_temp)) {
									firts_img_url = array.getJSONObject(1)
											.getJSONArray("fql_result_set")
											.getJSONObject(0)
											.getJSONArray("images")
											.getJSONObject(0)
											.getString("source");
									created_temp = created_temp1;
									Log.e("", "created_temp 1" + created_temp);
								}

							} else {
								firts_img_url = array.getJSONObject(1)
										.getJSONArray("fql_result_set")
										.getJSONObject(0)
										.getJSONArray("images")
										.getJSONObject(0).getString("source");
								created_temp = created_temp1;
								Log.e("", "created_temp 1" + created_temp);
							}

						}
					}
					if (array.getJSONObject(2).getJSONArray("fql_result_set")
							.length() > 0) {
						if (array.getJSONObject(2)
								.getJSONArray("fql_result_set")
								.getJSONObject(0).getJSONArray("images")
								.length() > 0) {
							String created_temp1 = array.getJSONObject(2)
									.getJSONArray("fql_result_set")
									.getJSONObject(0).getString("created");
							Log.e("",
									"created_temp.equals() 2 "
											+ created_temp.equals("")
											+ "created_temp " + created_temp);
							if (!created_temp.equals("")) {
								if (Long.valueOf(created_temp1) > Long
										.valueOf(created_temp))
									firts_img_url = array.getJSONObject(2)
											.getJSONArray("fql_result_set")
											.getJSONObject(0)
											.getJSONArray("images")
											.getJSONObject(0)
											.getString("source");
							} else {
								firts_img_url = array.getJSONObject(2)
										.getJSONArray("fql_result_set")
										.getJSONObject(0)
										.getJSONArray("images")
										.getJSONObject(0).getString("source");
							}

						}

					}
					new_photo_count = object_count1 + object_count2
							+ object_count3+object_count4;
					if (showfloating) {
						if (getSharedPreferences("congaixinh", 0).getBoolean(
								"floating", true)) {
							Log.e("", "firts_img_url " + firts_img_url);
							if (new_photo_count == 0) {
							} else {
							}
							
						} 
					} else {
						foregroundNotification(false);
					}

				}

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	protected void foregroundNotification(boolean b) {
		if (new_photo_count > 0) {
			Notification notification = new Notification(R.drawable.gx, "Có "
					+ new_photo_count + " ảnh mới", System.currentTimeMillis());
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			Intent notificationIntent = new Intent(this, MainActivity.class);
			notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
					notificationIntent, 0);
			notification.setLatestEventInfo(this, "Hội thích gái xinh	",
					"Mới cập nhật " + new_photo_count + " ảnh sexy mới",
					pendingIntent);
			 if (b) {
			 notificationIntent.putExtra("stop", true);
			 startForeground(7027, notification);
			 } else {
			mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			mNotificationManager.notify(7027, notification);
			 }

		} else if (new_photo_count == 0) {
			Notification notification = new Notification(R.drawable.gx,
					"Hội thích gái xinh	", System.currentTimeMillis());
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			Intent notificationIntent = new Intent(this, MainActivity.class);
			notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
					notificationIntent, 0);
			notification.setLatestEventInfo(this, "Hội thích ngắm gái xinh	",
					"Đã lâu bạn không vào app, hãy cùng vào với chúng tôi",
					pendingIntent);
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			mNotificationManager.notify(7027, notification);
		}

	}


	public Bitmap getCroppedBitmap(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		int r = 0;
		r = bitmap.getWidth() >= bitmap.getHeight() ? bitmap.getHeight()
				: bitmap.getWidth();
		// canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, r / 2,
				paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		// Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
		// return _bmp;
		return output;
	}

	static String url = "http://sphotos-d.ak.fbcdn.net/hphotos-ak-frc3/s2048x2048/972134_472484852832330_1303689092_n.jpg";

	public static Bitmap decodeSampledBitmapFromResource(int resId,
			int reqWidth, int reqHeight) throws MalformedURLException,
			IOException {
		Log.e("", firts_img_url);
		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(
				(InputStream) new URL(firts_img_url).getContent(), null,
				options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeStream(
				(InputStream) new URL(firts_img_url).getContent(), null,
				options);
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		int inSampleSize = 1;
		while (options.outWidth / inSampleSize / 2 >= reqWidth
				&& options.outHeight / inSampleSize / 2 >= reqHeight)
			inSampleSize *= 2;

		return inSampleSize;
	}

}
